<!--  -->
<template>
    <div class="page-container">
        <div class="header-panel">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="权限字符" prop="roleKey">
                    <el-input v-model="queryParams.roleKey" placeholder="请输入权限字符" clearable style="width: 240px"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                    <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd"
                        v-hasPermi="['system:user:add']">新增</el-button>

                    <el-button type="success" plain icon="el-icon-edit"  :disabled="single"
                        @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>

                    <el-button type="danger" plain icon="el-icon-delete"  :disabled="multiple"
                        @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>

                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange" size="medium"
            height="calc(100% - 100px)">
            <el-table-column type="selection" width="55" align="center" :selectable="isSelectable" />
            <el-table-column label="角色编号" align="center" prop="roleId"/>
            <el-table-column label="角色名称" align="center" prop="roleName" :show-overflow-tooltip="true" />
            <el-table-column label="权限字符" align="center" prop="roleKey" :show-overflow-tooltip="true" />
            <el-table-column label="显示顺序" align="center" prop="roleSort"  />
            <el-table-column label="创建时间" align="center" prop="createTime" >
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.roleKey !== 'surper-admin'">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:role:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:role:remove']">删除</el-button>
                    <!-- <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)"
                        v-hasPermi="['system:role:edit']">
                        <span class="el-dropdown-link">
                            <i class="el-icon-d-arrow-right el-icon--right"></i>更多
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check"
                                v-hasPermi="['system:role:edit']">数据权限</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="page.pageNum" :page-sizes="[50, 100, 200, 500]"
            :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
        </el-pagination>


        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="closeDialog">
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item prop="roleKey">
                    <span slot="label">
                        <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                            <i class="el-icon-question"></i>
                        </el-tooltip>
                        权限字符
                    </span>
                    <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
                </el-form-item>
                <el-form-item label="角色顺序" prop="roleSort">
                    <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="菜单权限">
                    <el-checkbox v-model="menuExpand"
                        @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
                    <el-checkbox v-model="menuNodeAll"
                        @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
                    <div style="min-height: 100px;max-height: 300px;overflow-y: auto;">
                        <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id"
                            :check-strictly="menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
                    </div>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="open = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    components: {},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
              // 勾选元素
            selection: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                roleName: undefined,
                roleKey: undefined,
                status: undefined
            },
            // 表单参数
            form: {},
            //分页条件
            page: {
                pageNum: 1,
                pageSize: 50,
                total: 0
            },
            // 角色表格数据
            roleList: [],
            // 菜单列表
            menuOptions: [],
            menuExpand: false,
            menuNodeAll: false,
            menuCheckStrictly: true,
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 表单校验
            rules: {
                roleName: [
                    { required: true, message: "角色名称不能为空", trigger: "blur" }
                ],
                roleKey: [
                    { required: true, message: "权限字符不能为空", trigger: "blur" }
                ],
                roleSort: [
                    { required: true, message: "角色顺序不能为空", trigger: "blur" }
                ]
            }
        }
    },
    computed: {},
    created() {
        this.getList();
    },
    mounted() { },
    methods: {

        /** 查询角色列表 */
        getList() {
            this.loading = true;
            this.$request({
                url: '/baseApi/system/role/pageList',
                method: 'get',
                params: {
                    ...this.queryParams, ...this.page
                }
            }).then((res) => {
                if (res.code === 200) {
                    this.loading = false;
                    this.roleList = res.data;
                }
            })
        },
        handleQuery() {
            this.page.current = 1;
            this.getList();
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selection = selection
            this.ids = selection.map(item => item.roleId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 更多操作触发
        handleCommand(command, row) {
            switch (command) {
                case "handleDataScope":
                    this.handleDataScope(row);
                    break;
                default:
                    break;
            }
        },
        /** 分配数据权限操作 */
        handleDataScope(row) {
            // this.reset();
            // const roleDeptTreeselect = this.getRoleDeptTreeselect(row.roleId);
            // getRole(row.roleId).then(response => {
            //     this.form = response.data;
            //     this.openDataScope = true;
            //     this.$nextTick(() => {
            //         roleDeptTreeselect.then(res => {
            //             this.$refs.dept.setCheckedKeys(res.checkedKeys);
            //         });
            //     });
            //     this.title = "分配数据权限";
            // });
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.title = "添加角色";
            this.getMenuTreeselect();
            this.open = true
        },
        getMenuTreeselect() {
            this.$request({
                url: 'baseApi/system/menu/treeselect',
                method: 'get',
                params: {}
            }).then((res) => {
                if (res.code === 200) {
                    const treeData = this.buildTree(res.data)
                    this.menuOptions = treeData;
                }
            })
        },
        /** 根据角色ID查询菜单树结构 */
        getRoleMenuTreeselect(roleId) {
            this.$request({
                url: 'baseApi/system/menu/roleMenuTreeselect',
                method: 'get',
                params: {
                    roleId: roleId
                }
            }).then((res) => {
                if (res.code === 200) {
                    const treeData = this.buildTree(res.data.menus)
                    this.menuOptions = treeData;
                    this.menuCheckStrictly = false;
                    this.$refs.menu.setCheckedKeys(res.data.checkedKeys);

                }
            })
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.title = "修改角色";
            this.form = this.selection[0] || row
            const roleId = this.form.roleId || this.ids
            this.getRoleMenuTreeselect(roleId);
            this.open = true
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const roleIds = row.roleId || this.ids;
            this.$confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request.post('/baseApi/system/role/delete', null, {
                    params: {
                        roleIds: roleIds
                    },
                    paramsSerializer: {
                        indexes: null
                    }
                }).then(res => {
                    this.handleQuery();
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                })

            }).catch(() => { })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let url = ''
                    if (this.form.roleId != undefined) {
                        url = '/baseApi/system/role/udpate'
                    } else {
                        url = '/baseApi/system/role/insert'
                    }
                    this.form.menuIds = this.getMenuAllCheckedKeys();
                    this.$request({
                        url: url,
                        method: 'post',
                        data: this.form
                    }).then((res) => {
                        if (res.code === 200) {
                            this.open = false;
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.handleQuery()
                        }
                    })
                }
            });
        },
        //改变页数据量
        handleSizeChange(val) {
            this.page.pageSize = val
            this.getList()
        },
        //改变当前页
        handleCurrentChange(val) {
            this.page.pageNum = val
            this.getList()
        },
        // 树权限（展开/折叠）
        handleCheckedTreeExpand(value, type) {
            if (type == 'menu') {
                let treeList = this.menuOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
                }
            } else if (type == 'dept') {
                let treeList = this.deptOptions;
                for (let i = 0; i < treeList.length; i++) {
                    this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
        },
        // 树权限（全选/全不选）
        handleCheckedTreeNodeAll(value, type) {
            if (type == 'menu') {
                this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
            } else if (type == 'dept') {
                this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
            }
        },

        // 所有菜单节点数据
        getMenuAllCheckedKeys() {
            // 目前被选中的菜单节点
            let checkedKeys = this.$refs.menu.getCheckedKeys();
            // 半选中的菜单节点
            let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
            checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
            return checkedKeys;
        },        /**
         * 递归生成树形结构
         * @param {Array} list 原始菜单列表
         * @param {Number} parentId 父节点ID，默认0（根节点）
         * @returns {Array} 树形结构数组
         */
        buildTree(list, parentId = 0) {
            // 1. 筛选当前父节点的子节点
            const children = list.filter(item => item.parentId === parentId);

            // 2. 按orderNum升序排序
            children.sort((a, b) => a.orderNum - b.orderNum);

            // 3. 递归处理子节点
            return children.map(child => ({
                ...child, // 复制当前节点属性
                id: child.menuId,
                label: child.menuName,
                children: this.buildTree(list, child.menuId) // 递归生成子树
            }));
        },
        // 控制表格行是否可勾选
        isSelectable(row, index) {
            // 禁止勾选 roleKey 为 'surper-admin' 的角色
            return row.roleKey !== 'surper-admin';
        },
        closeDialog() {
            this.menuCheckStrictly = true
            this.$refs.menu.setCheckedKeys([]);
            this.resetForm()
        },
        resetForm() {
            this.$data.form = this.$options.data().form
            this.$refs.form && this.$refs.form.resetFields()
        },
    },
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类样式
.el-dropdown {
    color: #409EFF;
    font-size: 12px;
}
</style>